package xin.marcher.module.quality.controller;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import xin.marcher.module.common.core.JsonResult;
import xin.marcher.module.common.exception.ProductBizException;
import xin.marcher.module.common.utils.JsonUtil;
import xin.marcher.module.quality.domain.dto.ItemQualityControlSurveyTaskDTO;
import xin.marcher.module.quality.domain.dto.ItemQualityControlSurveyTaskResultDO;
import xin.marcher.module.quality.domain.dto.ItemSurveyTaskDetailDTO;
import xin.marcher.module.quality.domain.request.ItemQualityControlSurveyTaskRequest;
import xin.marcher.module.quality.domain.request.SurveyFormRequest;
import xin.marcher.module.quality.domain.request.SurveyTaskRequest;
import xin.marcher.module.quality.service.ItemQualityControlSurveyTaskService;
import xin.marcher.module.rights.support.LoginUser;
import xin.marcher.module.rights.support.LoginUserHolder;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;


/**
 *
 */
@RestController
@RequestMapping("/quality/survey")
@Slf4j
public class ItemQualityControlSurveyTaskController {

    @Resource
    private ItemQualityControlSurveyTaskService surveyTaskService;

    @Resource
    private ItemQualityControlSurveyTaskService itemQualityControlSurveyTaskService;

    /**
     * 获取调查任务列表
     *
     * @param request
     * @return
     */
    @PreAuthorize("@rights.check('surveyTaskList', #token)")
    @PostMapping("/surveyTaskList")
    public JsonResult<List<ItemQualityControlSurveyTaskDTO>> surveyTaskList(String token, @RequestBody ItemQualityControlSurveyTaskRequest request) {
        try {
            return JsonResult.buildSuccess(itemQualityControlSurveyTaskService.surveyTaskList(request));
        } catch (Exception e) {
            log.error("system error: request={}", JSON.toJSONString(request), e);
            return JsonResult.buildError(e.getMessage());
        }
    }

    /**
     * 调查员认领任务
     *
     * @param request
     * @return
     */
    @PreAuthorize("@rights.check('claimedSurveyTask', #token)")
    @PostMapping("/claimedSurveyTask")
    public JsonResult<ItemQualityControlSurveyTaskResultDO> claimedSurveyTask(String token, @RequestBody ItemQualityControlSurveyTaskRequest request) {
        try {
            return JsonResult.buildSuccess(itemQualityControlSurveyTaskService.claimedSurveyTask(request));
        } catch (Exception e) {
            log.error("system error: request={}", JSON.toJSONString(request), e);
            return JsonResult.buildError(e.getMessage());
        }
    }

    /**
     * 获取调查任务详情数据
     *
     * @param request
     * @return
     */
    @PreAuthorize("@rights.check('qualitySurveyDetailList',#token)")
    @GetMapping("/detail/list")
    public JsonResult surveyTaskDetail(String token, @RequestBody SurveyTaskRequest request) {
        try {
            LoginUser user = LoginUserHolder.getLoginUser();
            if (Objects.isNull(user.getUserId()) || Objects.isNull(user.getUsername())) {
                return JsonResult.buildError("用户登录出错");
            }
            request.setUserId(user.getUserId().intValue());
            ItemSurveyTaskDetailDTO detailDTO = surveyTaskService.surveyTaskDetail(request);
            return JsonResult.buildSuccess(detailDTO);
        } catch (ProductBizException e) {
            log.error("biz error: request={}", JSON.toJSONString(request), e);
            return JsonResult.buildError(e.getErrorCode(), e.getErrorMsg());
        } catch (Exception e) {
            log.error("system error: request={}", JSON.toJSONString(request), e);
            return JsonResult.buildError(e.getMessage());
        }
    }

    /**
     * 发送调查单，并推送通知给用户
     *
     * @param request
     * @return
     */
    @PreAuthorize("@rights.check('qualitySurveySendForm',#token)")
    @PostMapping("/send/form")
    public JsonResult sendSurveyForm(String token, @RequestBody SurveyTaskRequest request) {
        try {
            LoginUser user = LoginUserHolder.getLoginUser();
            if (Objects.isNull(user.getUserId()) || Objects.isNull(user.getUsername())) {
                return JsonResult.buildError("用户登录出错");
            }
            request.setUserId(user.getUserId().intValue());
            surveyTaskService.sendSurveyForm(request);
            return JsonResult.buildSuccess();
        } catch (ProductBizException e) {
            log.error("biz error: request={}", JSON.toJSONString(request), e);
            return JsonResult.buildError(e.getErrorCode(), e.getErrorMsg());
        } catch (Exception e) {
            log.error("system error: request={}", JSON.toJSONString(request), e);
            return JsonResult.buildError(e.getMessage());
        }
    }

    /**
     * 审核资质证明材料
     *
     * @param request
     * @return
     */
    @PreAuthorize("@rights.check('qualitySurveyAuditMaterial',#token)")
    @PostMapping("/audit")
    public JsonResult auditQualityMaterials(String token, @RequestBody SurveyTaskRequest request) {
        try {
            LoginUser user = LoginUserHolder.getLoginUser();
            if (Objects.isNull(user.getUserId()) || Objects.isNull(user.getUsername())) {
                return JsonResult.buildError("用户登录出错");
            }
            request.setUserId(user.getUserId().intValue());
            surveyTaskService.auditQualityMaterials(request);
            return JsonResult.buildSuccess();
        } catch (ProductBizException e) {
            log.error("biz error: request={}", JSON.toJSONString(request), e);
            return JsonResult.buildError(e.getErrorCode(), e.getErrorMsg());
        } catch (Exception e) {
            log.error("system error: request={}", JSON.toJSONString(request), e);
            return JsonResult.buildError(e.getMessage());
        }
    }

    /**
     * 修改截止日期是否开启的状态
     * 开启/关闭商家提供资质期限
     *
     * @param request
     * @return
     */
    @PreAuthorize("@rights.check('qualitySurveyChangeDeadlineStatus',#token)")
    @PostMapping("/change/deadline/status")
    public JsonResult changeDeadlineStatus(String token, @RequestBody SurveyTaskRequest request) {
        try {
            LoginUser user = LoginUserHolder.getLoginUser();
            if (Objects.isNull(user.getUserId()) || Objects.isNull(user.getUsername())) {
                return JsonResult.buildError("用户登录出错");
            }
            request.setUserId(user.getUserId().intValue());
            surveyTaskService.changeDeadlineStatus(request);
            return JsonResult.buildSuccess();
        } catch (ProductBizException e) {
            log.error("biz error: request={}", JSON.toJSONString(request), e);
            return JsonResult.buildError(e.getErrorCode(), e.getErrorMsg());
        } catch (Exception e) {
            log.error("system error: request={}", JSON.toJSONString(request), e);
            return JsonResult.buildError(e.getMessage());
        }
    }

    /**
     * 修改资质上传的截止日期
     *
     * @param request
     * @return
     */
    @PreAuthorize("@rights.check('qualitySurveyChangeDeadline',#token)")
    @PostMapping("/change/deadline")
    public JsonResult updateDeadline(String token, @RequestBody SurveyTaskRequest request) {
        try {
            LoginUser user = LoginUserHolder.getLoginUser();
            if (Objects.isNull(user.getUserId()) || Objects.isNull(user.getUsername())) {
                return JsonResult.buildError("用户登录出错");
            }
            request.setUserId(user.getUserId().intValue());
            surveyTaskService.updateDeadline(request);
            return JsonResult.buildSuccess();
        } catch (ProductBizException e) {
            log.error("biz error: request={}", JSON.toJSONString(request), e);
            return JsonResult.buildError(e.getErrorCode(), e.getErrorMsg());
        } catch (Exception e) {
            log.error("system error: request={}", JSON.toJSONString(request), e);
            return JsonResult.buildError(e.getMessage());
        }
    }

    /**
     * 商家上传资质材料文件
     *
     * @param multipartHttpServletRequest
     * @return
     */
    @PreAuthorize("@rights.check('qualitySurveyUploadMaterials',#token)")
    @RequestMapping(value = "/upload/materials", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult uploadQualityMaterials(String token, MultipartHttpServletRequest multipartHttpServletRequest) {
        try {
            LoginUser user = LoginUserHolder.getLoginUser();
            if (Objects.isNull(user.getUserId()) || Objects.isNull(user.getUsername())) {
                return JsonResult.buildError("用户登录出错");
            }
            String surveyRequest = multipartHttpServletRequest.getParameter("requestParam");
            log.info(surveyRequest);
            SurveyFormRequest surveyFormRequest = JsonUtil.json2Object(surveyRequest, SurveyFormRequest.class);
            MultipartFile file = multipartHttpServletRequest.getFile("file");
            // 卖家登录时，userId即为卖家的sellerId
            surveyFormRequest.setSellerId(user.getUserId());
            surveyTaskService.uploadQualityMaterials(surveyFormRequest, file);
            return JsonResult.buildSuccess();
        } catch (ProductBizException e) {
            log.error("biz error: request={}", JSON.toJSONString(multipartHttpServletRequest), e);
            return JsonResult.buildError(e.getErrorCode(), e.getErrorMsg());
        }
    }

    /**
     * 运营下载资质材料做审核操作
     *
     * @param request
     * @return
     */

    @PreAuthorize("@rights.check('qualitySurveyDownloadMaterials',#token)")
    @GetMapping("/download/materials")
    public JsonResult downloadQualityMaterials(String token, @RequestBody SurveyTaskRequest request) {
        try {
            LoginUser user = LoginUserHolder.getLoginUser();
            if (Objects.isNull(user.getUserId()) || Objects.isNull(user.getUsername())) {
                return JsonResult.buildError("用户登录出错");
            }
            request.setUserId(user.getUserId().intValue());
            surveyTaskService.downLoadQualityMaterials(request);
            return JsonResult.buildSuccess();
        } catch (ProductBizException e) {
            log.error("biz error: request={}", JSON.toJSONString(request), e);
            return JsonResult.buildError(e.getErrorCode(), e.getErrorMsg());
        } catch (Exception e) {
            log.error("system error: request={}", JSON.toJSONString(request), e);
            return JsonResult.buildError(e.getMessage());
        }
    }
}
